<template>
  <div class="app-container">
    <div class="top">
      <div class="operate">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['taskMgmt:template:add']"
          >新增
        </el-button>
        <el-button
          icon="el-icon-edit"
          size="mini"
          :disabled="single != true"
          @click="handleUpdate()"
          v-hasPermi="['taskMgmt:template:edit']"
          >编辑
        </el-button>
        <el-button
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['taskMgmt:template:export']"
          >导出
        </el-button>
      </div>
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        label-width="68px"
      >
        <el-form-item prop="taskTemplateName">
          <el-input
            v-model="queryParams.taskTemplateName"
            placeholder="请输入关键字"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="taskType">
          <el-select
            v-model="queryParams.taskType"
            placeholder="请选择任务类型"
            clearable
            size="small"
          >
            <el-option
              v-for="item in dict.taskType"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.codevalue"
              :label="item.codename"
              :value="item.codevalue"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-table
      ref="Table"
      :data="list"
      tooltip-effect="dark"
      style="width: 100%"
      height="calc(100% - 44px - 50px)"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column label="模板编码" prop="taskTemplateCode">
      </el-table-column>
      <el-table-column label="任务模板名称" prop="taskTemplateName">
        <template slot-scope="{ row }">
          <el-button type="text" @click.stop="handleShowDetail(row)">{{
            row.taskTemplateName
          }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="总部模板名称" prop="parentTaskTemplateName">
      </el-table-column>
      <el-table-column label="任务类型" prop="taskType" width="140">
        <template slot-scope="{ row }">
          {{ taskTypeOptionsMap[row.taskType] }}
        </template>
      </el-table-column>
      <el-table-column label="是否品控关注任务" prop="isConcernedTask">
        <template slot-scope="{ row }">
          {{ row.isConcernedTask == "1" ? "是" : "否" }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="模板类型" prop="templateCategory">
        <template slot-scope="{ row }">
          {{ getTemplateCategoryName(row.templateCategory) }}
        </template>
      </el-table-column> -->
      <el-table-column label="状态" prop="status">
        <template slot-scope="{ row }">
          {{ row.status == "1" ? "已启用" : "已停用" }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="260" fixed="right">
        <template slot-scope="{ row }">
          <template v-if="row.templateCategory == 'custom'">
            <el-button
              v-if="buttonPermi(['taskMgmt:template:design'], true)"
              type="text"
              @click.stop="handleDesignForm(row)"
              >设计表单</el-button
            >
            <el-button
              v-if="
                buttonPermi(
                  ['taskMgmt:template:deactivate'],
                  row.status === '1'
                )
              "
              type="text"
              @click.stop="handleDeactivate(row)"
              >停用</el-button
            >
            <el-button
              v-if="
                buttonPermi(['taskMgmt:template:activate'], row.status === '0')
              "
              type="text"
              @click.stop="handleActivate(row)"
              >启用</el-button
            >
            <el-button
              v-if="buttonPermi(['taskMgmt:template:edit'], true)"
              type="text"
              @click.stop="handleUpdate(row)"
              >编辑</el-button
            >
            <!-- 停用状态的模板才可以删除 -->
            <el-button
              v-if="
                buttonPermi(['taskMgmt:template:remove'], row.status === '0')
              "
              type="text"
              @click.stop="handleDelete(row)"
              >删除</el-button
            >
          </template>
          <el-button
            v-if="buttonPermi(['taskMgmt:template:preview'], true)"
            type="text"
            @click.stop="handlePreviewForm(row)"
            >预览</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      :total="pager.total"
      :page.sync="pager.pageNum"
      :limit.sync="pager.pageSize"
      @pagination="getList"
    />
    <!-- 新增编辑模板 -->
    <DetailDialog
      :visible.sync="detailDialog.visible"
      :row="detailDialog.row"
      :disabled="detailDialog.disabled"
      @refresh="getList"
    ></DetailDialog>
    <!-- 查看总部模板 -->
    <HeadquartersDetailDialog
      :visible.sync="headquartersDetailDialog.visible"
      :row="headquartersDetailDialog.row"
    ></HeadquartersDetailDialog>
    <!-- 表单设计 -->
    <DesignDialog
      :visible.sync="designDialog.visible"
      :row="designDialog.row"
      @refresh="getList"
    ></DesignDialog>
    <!-- 表单预览 -->
    <PreviewDialog
      :visible.sync="previewDialog.visible"
      :formFieldConfig="previewDialog.formFieldConfig"
      :formName="previewDialog.formName"
      :renderingMode="previewDialog.renderingMode"
    ></PreviewDialog>
  </div>
</template>
<script>
import DetailDialog from "./detailDialog";
import HeadquartersDetailDialog from "./headquartersDetailDialog";
import DesignDialog from "../components/formDesign/designDialog";
import PreviewDialog from "../components/formDesign/previewDialog";
import {
  getTaskTemplateList,
  saveTaskTemplate,
  deleteTaskTemplate,
  getTaskTemplateDesign,
  exportTaskTemplate,
} from "@/api/taskMgmt/template";
import { downloadFile } from "@/utils/file";
import { checkPermi } from "@/utils/permission";
export default {
  name: "Template",
  components: {
    DetailDialog,
    HeadquartersDetailDialog,
    DesignDialog,
    PreviewDialog,
  },
  dicts: ["taskType"],
  data() {
    return {
      queryParams: {
        taskTemplateName: "",
        taskType: "",
        status: "",
        templateCategory: "custom",
      },
      statusOptions: [
        {
          codevalue: "1",
          codename: "已启用",
        },
        {
          codevalue: "0",
          codename: "已停用",
        },
      ],
      list: [],
      single: null,
      loading: false,
      pager: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
      },
      detailDialog: {
        visible: false,
        row: null,
        disabled: false,
      },
      headquartersDetailDialog: {
        visible: false,
        row: null,
      },
      designDialog: {
        visible: false,
        row: null,
      },
      // 表单预览弹窗
      previewDialog: {
        visible: false,
        formFieldConfig: {},
        formName: null,
        renderingMode: "1",
      },
      exportLoading: false,
    };
  },
  computed: {
    taskTypeOptionsMap() {
      return this.dictToMap(this.dict.taskType);
    },
  },
  created() {
    //获取列表数据
    this.getList();
    window.addEventListener("resize", this.resizeTable);
  },
  methods: {
    // 列表按钮显示权限
    buttonPermi(permis, flag) {
      return checkPermi(permis) && flag;
    },
    getList() {
      this.loading = true;
      this.single = null;
      const { pageNum, pageSize } = this.pager;
      const params = {
        query: {
          ...this.queryParams,
        },
        pageNum,
        pageSize,
      };
      getTaskTemplateList(params)
        .then((res) => {
          this.list = res.rows;
          this.pager.total = res.total;
          this.loading = false;
        })
        .catch(() => {
          this.list = [];
          this.pager.total = 0;
          this.loading = false;
        });
    },
    handleSelectionChange(selection) {
      if (selection.length > 1) {
        this.single = false;
      } else if (selection.length == 1) {
        this.single = true;
      } else {
        this.single = null;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.detailDialog.row = null;
      this.detailDialog.visible = true;
      this.detailDialog.disabled = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (!row) {
        row = this.$refs.Table.selection[0] || null;
      }

      if (row.templateCategory == "base") {
        this.headquartersDetailDialog.row = row;
        this.headquartersDetailDialog.visible = true;
      } else {
        this.detailDialog.row = row;
        this.detailDialog.visible = true;
        this.detailDialog.disabled = false;
      }
    },
    /** 查看详情按钮操作 */
    handleShowDetail(row) {
      this.detailDialog.row = row;
      this.detailDialog.visible = true;
      this.detailDialog.disabled = true;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.status != "0") {
        this.msgWarning("启用状态的任务模板不允许删除！");
        return;
      }
      let ids = "";
      let msg = "";
      if (row) {
        ids = row.id;
        msg = `确定删除${row.taskTemplateName}吗？`;
      } else {
        const selection = this.$refs.Table.selection;
        ids = selection.map((ele) => ele.id).join(",");
        msg = `确定删除所选的${selection.length}条记录吗？`;
      }
      this.$confirm(msg, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return deleteTaskTemplate(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 表单按钮操作 */
    handleDesignForm(row) {
      this.designDialog.row = row;
      this.designDialog.visible = true;
    },
    /** 停用按钮操作 */
    handleDeactivate(row) {
      this.$confirm(`确定停用${row.taskTemplateName}吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          const param = {
            id: row.id,
            status: "0",
          };
          return saveTaskTemplate(param);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        });
    },
    /** 启用按钮操作 */
    handleActivate(row) {
      this.$confirm(`确定启用${row.taskTemplateName}吗？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          const param = {
            id: row.id,
            status: "1",
          };
          return saveTaskTemplate(param);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("操作成功");
        });
    },
    /** 预览按钮操作 */
    handlePreviewForm(row) {
      if (!row.taskTemplateCode) {
        this.msgWarning("当前任务模板不可预览！");
        return;
      }
      getTaskTemplateDesign(row.taskTemplateCode)
        .then((res) => {
          this.previewDialog.formFieldConfig = res.data;
          this.previewDialog.formName = row.taskFormName;
          this.previewDialog.renderingMode = row.renderingMode;
          this.previewDialog.visible = true;
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.exportLoading = true;
      const param = {
        query: {
          ...this.queryParams,
        },
      };
      exportTaskTemplate(param)
        .then((res) => {
          downloadFile(
            res.file,
            decodeURIComponent(res.name) ||
              `任务模板${this.parseTime(new Date(), "{y}{m}{d}{h}{i}{s}")}.xlsx`
          );
        })
        .finally(() => {
          this.exportLoading = false;
        });
    },
    // getTemplateCategoryName(templateCategory) {
    //   let res = "";
    //   switch (templateCategory) {
    //     case "base":
    //       res = "总部模板";
    //       break;
    //     case "custom":
    //       res = "自定义模板";
    //       break;
    //     default:
    //       break;
    //   }
    //   return res;
    // },
    resizeTable() {
      if (this.$refs.Table) {
        this.$refs.Table.doLayout();
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeTable);
  },
};
</script>
<style lang="scss" scoped>
.top {
  height: 44px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}
.pagination-container {
  margin: 0;
}
</style>
